package ac.il.technion.cs236635.project.core;

import java.io.IOException;
import java.util.Properties;
import java.util.Random;

import org.apache.log4j.Logger;

import ac.il.technion.cs236635.project.core.server.ServerJob;

public class JobsSubmitter implements Runnable {

	private volatile boolean finished = false;
	
	private double rate = 0.5;
	
	private long interval = 2000;
	
	private int serversNum = 5;
	
	private String clientEndpoint = "";

	private String clientName = "";
	
	private Logger log = Logger.getLogger( JobsSubmitter.class);
	
	private int jobsToSend = 1;
	
	public JobsSubmitter( ) {
		Properties properties = new Properties( );
		try {
			properties.load( JobsSubmitted.class.getClassLoader().getResourceAsStream( "client.properties"));
		} catch (IOException e) {
			e.printStackTrace();
			return; // No reason to contine once exception has been thrown
		}
		// Read the properties from file and initialize fields
		serversNum = Integer.valueOf( properties.getProperty( "numberOfServers", "5"));
		
		interval = Long.valueOf( properties.getProperty( "timeoutToWait", "2000"));
		
		rate = Double.valueOf( properties.getProperty( "rate", "0.5"));
		
		clientEndpoint = properties.getProperty( "clientEndpoint");
		
		clientName = properties.getProperty( "clientName");
		
		jobsToSend = Integer.valueOf( properties.getProperty( "jobsToSend"));
	}
	
	@Override
	public void run() {
		Random rnd = new Random( );
		int sended = 0;
		int id = 0;
		while ( !finished && sended != jobsToSend) {
			try {
				Thread.sleep( (long)Utility.genNextExp(rate, interval, serversNum)); // Wait till next job arrives
			} catch (InterruptedException e) {
				log.error(e);
			}
			ServerJob job = new ServerJob( );
			job.setClientEndpoint( clientEndpoint);
			job.setClientName( clientName);
			job.setJobId( ++id);
			JobsSubmitted.getInstance().submit(job);
			++sended;
			// Next iteration: generate event sleep and then produce new job.
			log.info( "CREATED: New job created, job id: " + job.getJobId( ));
		}
	}

	public void finish( ) {
		finished = true;
	}
	
}
